import { onBeforeUnmount, nextTick, ref } from 'vue'
import { protocol, hostname } from '@/utils/request/config'
import { message } from 'ant-design-vue'

// WebSocket视频流播放
export function useWebSocketPlayer({
  streamUrl = 'rtsp://stream.strba.sk:1935/strba/VYHLAD_JAZERO.stream',
  elementId = 'panorama-video-ws'
} = {}) {
  const streamUrlRef = ref(streamUrl)
  const isActiveRef = ref(false)

  const getVideoElement = () => document.querySelector(`#${elementId}`)

  // 检查是否正在播放
  const isPlaying = () => getVideoElement()?.hasAttribute('url') || false

  // 从URL中提取流标识符
  const extractStreamSuffix = (url) => {
    if (!url) return ''
    try {
      const { pathname } = new URL(url)
      return pathname.split('/').filter(Boolean).pop() || ''
    } catch {
      return url.split('/').pop() || ''
    }
  }

  const buildWsUrl = (url) => `${protocol}//${hostname}:8000/${extractStreamSuffix(url)}`

  // 播放WebSocket视频流
  const playStream = async () => {
    if (!streamUrlRef.value?.trim()) {
      message.error('请输入有效的视频流地址')
      return false
    }

    try {
      await nextTick()
      const videoWs = getVideoElement()
      if (!videoWs) throw new Error('找不到video-ws元素')

      videoWs.setAttribute('url', buildWsUrl(streamUrlRef.value))
      isActiveRef.value = true
      message.success('开始加载视频流')
      return true
    } catch (error) {
      message.error(error.message || '初始化播放器失败')
      isActiveRef.value = false
      return false
    }
  }

  // 停止视频流播放
  const stopStream = () => {
    const videoWs = getVideoElement()
    if (!videoWs || !isPlaying()) return false

    videoWs.removeAttribute('url')
    isActiveRef.value = false
    return true
  }

  // 在组件卸载前清理资源
  onBeforeUnmount(() => {
    isPlaying() && stopStream()
  })

  return {
    streamUrl: streamUrlRef,
    isPlaying,
    playStream,
    stopStream
  }
}
